<template>
    <div class="page">
        <div class="m1">
            <van-image width="100%" src="https://pic.solux.cn/Mobile/00_2020/0512/m1.jpg" />
        </div>
        <div class="m2" id="m2">
            <h1>“松霖·家”</h1>
            <p>为全面满足“装修一个家”的梦想而生</p>
            <div class="addr">
                地址：湖里大道42号
            </div>
            <van-form @submit="onSubmit">
                <van-field
                    v-model="param.username"
                    name="username"
                    placeholder="请问您怎么称呼？">
                </van-field>
                <van-field
                    v-model="param.userphone"
                    type="tel"
                    name="userphone"
                    placeholder="您的联系电话是？">
                </van-field>
                <div class="btn">
                    <van-button round block type="info" color="linear-gradient(#deb580, #b68e54)" native-type="submit">
                    我要进店
                    </van-button>
                </div>
            </van-form>
        </div>
        <div v-for="(item,index) in imageList" :key="index">
            <img v-lazy="item" />
        </div>
        <van-dialog v-model="showDialog" title="手机验证" :beforeClose="beforeClose" show-cancel-button>
            <div class="d_tips">短信验证码已发送至{{param.userphone}}</div>
            <div class="d_ct">
                <van-form>
                    <van-field
                        v-model="param.vcode"
                        center
                        clearable
                        placeholder="请输入短信验证码"
                        >
                        <template #button>
                            <van-button size="small" v-if="time == 0" @click="sendAction">发送验证码</van-button>
                            <van-button size="small" v-else><van-count-down ref="countDown" :time="time" @finish="finish" format="重新获取(ss)"/></van-button>
                        </template>
                    </van-field>
                </van-form>
            </div>
        </van-dialog>
    </div>
</template>

<script>
import { mapActions } from 'vuex'
import { validate } from '@/utils/common.js'
import { msgSave,captchaGt,wxShare,wxConfig,sendUrl } from '@/utils/getData';
import wx from 'weixin-js-sdk';
export default {
    name: 'home',
    data() {
        return {
            imageList:[
                'https://pic.solux.cn/Mobile/00_2020/0512/m3.jpg',
                'https://pic.solux.cn/Mobile/00_2020/0512/m4.gif',
                'https://pic.solux.cn/Mobile/00_2020/0512/m5.jpg',
                'https://pic.solux.cn/Mobile/00_2020/0512/m6.jpg',
                'https://pic.solux.cn/Mobile/00_2020/0512/m7.jpg',
                'https://pic.solux.cn/Mobile/00_2020/0512/m8.jpg',
                'https://pic.solux.cn/Mobile/00_2020/0512/m9.jpg',
            ],
            param:{
                username:'',
                userphone:'',
                remark:'“松霖·家”厦门S1-今日头条',
                vcheck:'1', //vcheck为1时，需要短信验证码，参考20190214
                vcode:''
            },
            codeParam:{
                uname:'',
                type:'check',
                geetest_challenge:'',
                geetest_validate:'',
                geetest_seccode:''
            },
            formRules:{
                username:[
                    {  required: true, message: '请问您怎么称呼？'},
                ],
                userphone:[
                    {  required: true, message: '您的联系电话是？'},
                    {  pattern:/^1[3456789]\d{9}$/, message: '手机格式不正确'}
                ]
            },
            obj:'',
            showDialog:false, //是否显示短信弹窗
            time: 0,
        }
    },
    mounted: function() {
        this.initGt();

        let ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            this.wxShareFun();
        }
    },
    methods:{
        ...mapActions([
            'login'
        ]),
        onSubmit(values) {
            try{
                if(validate(values,this.formRules)){
                    this.codeParam.uname = this.param.userphone;
                    this.showDialog = true;
                }
            }catch (e) {
                this.$toast({
                    icon:'fail',
                    message:e.message,
                    forbidClick:false
                });
            }
        },
        async postData(){
            const res = await msgSave(this.param);
            if(res.status == 'error'){
                this.$toast({
                    icon:'fail',
                    message:res.msg,
                    forbidClick:false
                });
            }else{
                this.$toast({
                    icon:'success',
                    message:res.msg,
                    forbidClick:false
                });
                meteor.track("form", {convert_id: "1666474702578695"});
                this.showDialog = false;
                this.login({sname:this.param.username});
                this.$router.push('/success');
            }
        },
        goPath(url){
            this.$router.push(url);
        },
        async _sendVerify(){
            const res = await sendUrl(this.codeParam);
            if(res.success){
                this.$toast({
                    icon:'success',
                    message:res.success,
                    forbidClick:false
                });
            }else{
                this.$toast({
                    icon:'fail',
                    message:res.error,
                    forbidClick:false
                });
                this.time = 0;
            }
        },
        async initGt() {
            const res = await captchaGt();
            if(res.success){
                // 使用initGeetest接口
                // 参数1：配置参数
                // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
                initGeetest({
                    // 以下 4 个配置参数为必须，不能缺少
                    gt: res.gt,
                    challenge: res.challenge,
                    offline: !res.success, // 表示用户后台检测极验服务器是否宕机
                    new_captcha: res.new_captcha, // 用于宕机时表示是新验证码的宕机

                    product: "bind", // 产品形式，包括：float，popup
                    width: "300px"
                    // 更多配置参数说明请参见：http://docs.geetest.com/install/client/web-front/
                }, this.handlerEmbed);
            }else{
                this.$toast({
                    icon:'fail',
                    message:res.message,
                    forbidClick:false
                });
            }
        },
        handlerEmbed(captchaObj) {
            var that = this;
            captchaObj.onReady(function() {
                that.obj = captchaObj
            }).onSuccess(function() {
                var result = captchaObj.getValidate();
                if (!result) {
                    that.$toast({
                        icon:'fail',
                        message:'请完成验证',
                        forbidClick:false
                    });
                    return false;
                }
                that.codeParam.geetest_challenge = result.geetest_challenge;
                that.codeParam.geetest_validate = result.geetest_validate;
                that.codeParam.geetest_seccode = result.geetest_seccode;

                that.time = 60 * 1000;
                that._sendVerify();
            });
        },
        sendAction(){
            this.obj.verify();
        },
        finish(){
            this.time = 0;
        },
        async wxShareFun(){
            const res = await wxShare({url_name:'s20200511'});
            if(res.status == "success"){
                const res2 = await wxConfig({'keyUrl': window.location.href})
                if(res2.success){
                    wx.config({
                        debug: false,
                        appId: res2.success.appId,
                        timestamp: res2.success.timestamp,
                        nonceStr: res2.success.nonceStr,
                        signature: res2.success.signature,
                        jsApiList: ['updateAppMessageShareData', 'hideMenuItems', 'updateTimelineShareData']
                    });
                    
                    wx.ready(function () {
                        //分享给朋友
                        wx.updateAppMessageShareData({
                            title: res.data.share_title, // 分享标题
                            desc: res.data.share_desc, // 分享描述
                            link: 'https://www.solux.cn/wap/subject-s20200511.html', // 分享链接
                            imgUrl: res.data.share_image, // 分享图标
                            success: function () {
                                // 用户确认分享后执行的回调函数
                            }
                        });
                        //分享朋友圈
                        wx.updateTimelineShareData({
                            title: res.data.share_title, // 分享标题
                            link: 'https://www.solux.cn/wap/subject-s20200511.html', // 分享链接
                            imgUrl: res.data.share_image, // 分享图标
                            success: function () {
                                // 用户确认分享后执行的回调函数
                            }
                        });
                    });
                }
            }
        },
        beforeClose(action, done){
            if(action == 'confirm'){
                if(!this.param.vcode){
                    this.$toast({
                        icon:'fail',
                        message:'请输入短信验证码',
                        forbidClick:false
                    });
                    done(false);
                }else{
                    this.postData();
                    done(false);
                }
            }else{
                done();
            }
        }
    }
}
</script>
<style scoped>
    .m2{text-align:center;color:#000;padding:50px 0;}
    .m2 h1{font-size:36px;font-weight:normal;line-height:48px;}
    .m2 p{font-size:20px;line-height:34px;}
    .m2 .addr{font-size:18px;line-height:34px;margin-top:19px;}
    .m2 .van-form{width:280px;margin:0 auto;overflow: hidden;padding-top:10px;}
    .m2 .van-form .van-cell{border:1px solid #666;margin-top:13px;}
    .m2 .van-form .van-cell >>> input{text-align:center;}
    .m2 .van-form .btn{margin-top:20px;}
    .m2 .van-form .van-button__text{font-size:18px;font-weight:bold;}

    .d_tips{text-align:center;font-size:12px;color:#999;margin-top:20px;}
    .d_ct{padding:20px;}
    .d_ct >>> .van-field__value{border-bottom:1px solid #EAEAEA;}
</style>